package servlet;

import entity.Person;
import entity.PersonService;
import com.octo.captcha.service.CaptchaServiceException;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.CaptchaServiceSingleton;
import util.Mail;
import util.Utilities;

/**
 *
 * @author Francis
 */
public class RegistrationServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String loginName = request.getParameter("loginname");
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        int birth_year = Integer.parseInt(request.getParameter("birth_year"));
        int birth_month = Integer.parseInt(request.getParameter("birth_month"));
        String gender = request.getParameter("gender");
        String address = request.getParameter("address");
        String password = request.getParameter("password9");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String captchaCode = request.getParameter("captchacode");
        boolean notify = request.getParameter("notify") == null ? false : true;
        boolean agreement = request.getParameter("agreement") == null ? false : true;
        boolean isCorrectCaptcha = false;

        //TODO: move into the if scope later
        HttpSession session = request.getSession(true);
        session.setAttribute("loginname", loginName);
        session.setAttribute("firstname", firstname);
        session.setAttribute("lastname", lastname);
        session.setAttribute("birth_year", Integer.toString(birth_year));
        session.setAttribute("birth_month", Integer.toString(birth_month));
        session.setAttribute("gender", gender);
        session.setAttribute("address", address);
        session.setAttribute("email", email);

        //convert to UTF-8 for internal processing
        firstname = Utilities.toUTF8(request.getParameter("firstname"));
        lastname = Utilities.toUTF8(request.getParameter("lastname"));
        
        
        //TDOD: server side data validation

        try {
            isCorrectCaptcha = CaptchaServiceSingleton.getInstance().validateResponseForID(session.getId(), captchaCode);
        } catch (CaptchaServiceException e) {
            //should not happen, may be thrown if the id is not valid
        }

        if (!agreement) {
            response.sendRedirect("Registration.jsp?msg=5");
            //TODO: you should agree withthe agreement
            return;
        } else if (Utilities.isValid(password) && !password.equals(repassword)) {
            response.sendRedirect("Registration.jsp?msg=4");
            return;
        } else if (!isCorrectCaptcha) {
            response.sendRedirect("Registration.jsp?msg=1");
            return;
        } else if (PersonService.isLoginNameExist(loginName)) {
            //todo: check for account activation, resend comfirmation letter if necessary
            response.sendRedirect("Registration.jsp?msg=2");
            return;
        } else if (PersonService.isEmailExist(email)) {
            response.sendRedirect("Registration.jsp?msg=3");
            return;
        } else {
            Person p = new Person();
            p.setLoginname(loginName);
            p.setFirstname(firstname);
            p.setLastname(lastname);
            p.setPassword(password);
            p.setBirthYear(birth_year);
            p.setBirthMonth(birth_month);
            p.setGender(gender);
            p.setAddress(address);
            p.setEmail(email);
            p.setRegtertime(Utilities.now());
            p.setMailPromotion(notify);
            p.setActivated(false);
            p.setRating(0);
            p.setRegterIP(request.getRemoteAddr());

            PersonService.create(p);

            // Using the MD5Hash     
            String code = PersonService.getActivationCode(p);

            Mail.sendMail(email, "Confirmation mail for 二手易", "http://localhost:8084/2handeasy/Activation.jsp?code=" + code);
            response.sendRedirect("Registered.jsp");
            return;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
